package com.atmilan.quartz.utils.source;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.atmilan.quartz.constant.enums.BarCodeEnum;
import com.atmilan.quartz.constant.enums.CategoryTypeEnum;
import com.atmilan.quartz.constant.enums.ProductTypeEnum;
import com.atmilan.quartz.model.dto.crmeb.StoreProductCrmebRequest;
import com.atmilan.quartz.model.dto.orange.OrangeProductResDTO.OrangeData.OrangeGoodsRes.Sku.SkuValue;
import com.atmilan.quartz.model.entity.buyer.Supplier;
import com.atmilan.quartz.model.entity.crmeb.CategoryMatch;
import com.atmilan.quartz.model.entity.crmeb.StoreBrand;
import com.atmilan.quartz.model.entity.crmeb.StoreProductAttr;
import com.atmilan.quartz.model.entity.orange.OrangeProduct;
import com.atmilan.quartz.model.entity.orange.OrangeProductSku;
import com.atmilan.quartz.model.entity.orange.OrangeProductSkuChannel;
import com.atmilan.quartz.service.ICategoryMatchService;
import com.atmilan.quartz.service.IStoreBrandService;
import com.atmilan.quartz.service.ISupplierService;
import com.atmilan.quartz.sync.push.crmeb.domain.StoreProductAttrValueRequest;
import com.atmilan.quartz.sync.push.crmeb.enums.CrmebMerchantEnums;
import com.atmilan.quartz.utils.PriceUtil;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;

/**
 * 处理源数据转换和计算相关信息
 * @Description: 
 * @author daigb
 * @date 2021-03-05
 */
@Service
public class SourceOrangeProductUtil {
    @Autowired
    IStoreBrandService storeBrandService;
    @Autowired
    ICategoryMatchService categoryMatchService;
    @Autowired
    ISupplierService supplierService;
    @Autowired
    PriceUtil priceUtil;

    /**
     *
     * 构建DO对象（orange）
     * @param product
     * @param skus
     * @return
     */
    public StoreProductCrmebRequest buildOrangeProduct(OrangeProduct product, List<OrangeProductSku> skus,List<OrangeProductSkuChannel> channelList,Integer tempId) {
        // 主商品对象
        StoreProductCrmebRequest productRequest = new StoreProductCrmebRequest();
        try {
            // 分类
            CategoryMatch categoryMatch = categoryMatchService.getOne(Wrappers.<CategoryMatch>lambdaQuery()
                    .eq(CategoryMatch::getType, CategoryTypeEnum.ORANGE.getCode())
                    .eq(CategoryMatch::getOthCategoryId, product.getFirstCateName())
                    .eq(CategoryMatch::getOthCategoryName, product.getSecondCateName())
                    .eq(CategoryMatch::getOthCategoryType,product.getThirdCateName())
                    .last("LIMIT 1"));
            categoryMatchService.unMatchCategory(categoryMatch,product.getFirstCateName(),product.getSecondCateName(),product.getThirdCateName(),CategoryTypeEnum.ORANGE);
            // 复制重量
            if(null != categoryMatch) {
            	CategoryMatch supCategoryMatch = categoryMatchService.getById(categoryMatch.getCategoryId());
            	categoryMatch.setWeight(Optional.ofNullable(supCategoryMatch).orElse(new CategoryMatch()).getWeight());
            }
            if(null == categoryMatch){
                return productRequest;
            }
            Integer categoryId = categoryMatch.getCategoryId();
            productRequest.setCateId(categoryId);
            productRequest.setCateIds(Collections.singletonList(categoryId));
            productRequest.setWeight(null != categoryMatch ? categoryMatch.getWeight() : BigDecimal.ONE);

            List<String> imageList = JSONArray.parseArray(product.getImageList(), String.class);
            // 平台原价
            BigDecimal otPrice = channelList.stream().filter(e-> StringUtils.isNotBlank(e.getOriginalPrice().toString())).map(OrangeProductSkuChannel::getOriginalPrice).map(BigDecimal::valueOf).min(BigDecimal::compareTo).orElse(BigDecimal.ZERO);
            otPrice = priceUtil.rmb2EurStatic(otPrice);
            // 售价
            BigDecimal price =channelList.stream().map(OrangeProductSkuChannel::getPrice).map(BigDecimal::valueOf).min(BigDecimal::compareTo).orElse(BigDecimal.ZERO);
            // 大于或小于指定折扣, 原价置空
            BigDecimal otPriceRmb = priceUtil.eur2RmbStatic(otPrice);
       	 	boolean discount20 = otPriceRmb.compareTo(BigDecimal.ZERO) == 0 ? false : new BigDecimal("2").compareTo(price.divide(otPriceRmb, 2, RoundingMode.HALF_UP)) <= 0;
       	 	boolean discount1 = otPriceRmb.compareTo(BigDecimal.ZERO) == 0 ? false : new BigDecimal("0.1").compareTo(price.divide(otPriceRmb, 2, RoundingMode.HALF_UP)) >= 0;
            if(discount20 || discount1) {
            	otPrice = BigDecimal.ZERO;
            }
            // 品牌对应
            StoreBrand buyerStoreBrand = storeBrandService.getOne(Wrappers.<StoreBrand>lambdaQuery()
                    .eq(StoreBrand::getEnName, product.getBrandName())
                    .eq(StoreBrand :: getType, ProductTypeEnum.ORANGE)
                    .last("LIMIT 1"));
            storeBrandService.unMatchBrand(buyerStoreBrand,null,product.getBrandName(),ProductTypeEnum.ORANGE);
            StoreBrand storeBrand = (null != buyerStoreBrand && null != buyerStoreBrand.getSuperId()) ? storeBrandService.getById(buyerStoreBrand.getSuperId()) : storeBrandService.getById(5429);
            /***** 处理对象构建 *******/
            String barCode = BarCodeEnum.ORANGE.getCode() + product.getItemId() + "-"+tempId;
            List<StoreProductAttr> attrList = new ArrayList<>();
            List<StoreProductAttrValueRequest> attrValueList = new ArrayList<>();

            List<String> sizeValueList = new ArrayList<>();
            // 规格
            StoreProductAttr storeProductAttr = new StoreProductAttr();
            storeProductAttr.setAttrName("尺寸");
            storeProductAttr.setType(0);
            storeProductAttr.setBarCode(barCode);
            for (OrangeProductSkuChannel channel : channelList) {
            	// 大于或小于指定折扣, 原价置空
                BigDecimal priceValRmb = BigDecimal.valueOf(channel.getPrice());
                BigDecimal otPriceValRmb = BigDecimal.valueOf(channel.getOriginalPrice());
           	 	boolean discountVal20 = otPriceValRmb.compareTo(BigDecimal.ZERO) == 0 ? false : new BigDecimal("2").compareTo(priceValRmb.divide(otPriceValRmb, 2, RoundingMode.HALF_UP)) <= 0;
           	 	boolean discountVal1 = otPriceValRmb.compareTo(BigDecimal.ZERO) == 0 ? false : new BigDecimal("0.1").compareTo(priceValRmb.divide(otPriceValRmb, 2, RoundingMode.HALF_UP)) >= 0;
                if(discountVal20 || discountVal1) {
                	otPriceValRmb = BigDecimal.ZERO;
                }
                // value对象
                StoreProductAttrValueRequest storeProductAttrValue = new StoreProductAttrValueRequest();
                storeProductAttrValue.setSourceSkuId(channel.getSkuId()+"-"+channel.getChannelType());
                storeProductAttrValue.setStock(channel.getStock());
                storeProductAttrValue.setPrice(priceValRmb);
                storeProductAttrValue.setImage(imageList.get(0));
                storeProductAttrValue.setCost(BigDecimal.valueOf(channel.getPrice()));
                storeProductAttrValue.setSourceCost(BigDecimal.valueOf(channel.getPrice()));
                storeProductAttrValue.setBarCode(barCode);
//                storeProductAttrValue.setOtPrice(priceUtil.rmb2EurStatic(otPriceValRmb));
                storeProductAttrValue.setSkuCode(channel.getItemCode());
                //发货地
                storeProductAttrValue.setTempId(tempId);
                OrangeProductSku orangeProductSku = skus.stream().filter(e -> channel.getSkuId().equals(e.getSkuId())).collect(Collectors.toList()).get(0);
                storeProductAttrValue.setWeight(ObjectUtils.isNotEmpty(orangeProductSku.getWeight()) ? BigDecimal.valueOf(orangeProductSku.getWeight()) : null);
                LinkedHashMap<String, String> linkedMap = new LinkedHashMap<>();
                List<String> suk = new ArrayList<>();
                List<SkuValue> skuValues = JSONArray.parseArray(orangeProductSku.getSkuValues(), SkuValue.class);
                List<SkuValue> skuValueList = skuValues.stream().peek(e -> e.setSkuValue(e.getSkuValue().replace(",", "-"))).collect(Collectors.toList());
                //尺寸
                String size = skuValueList.stream().map(SkuValue::getSkuValue).collect(Collectors.joining("-"));
                if(orangeProductSku.getUnitQuantity() != 1){
                    size = size +"-"+ orangeProductSku.getUnitQuantity()+orangeProductSku.getUnit();
                }
                if(StringUtils.isNotBlank(size)){
                    linkedMap.put("尺寸", size);
                    if(!sizeValueList.contains(size)){
                        sizeValueList.add(size);
                    }
                    suk.add(size);
                }
                //suk
                storeProductAttrValue.setSuk(String.join(",", suk));
                storeProductAttrValue.setAttrValue(linkedMap);
                attrValueList.add(storeProductAttrValue);
            }
            //attr对象
            if (CollectionUtils.isNotEmpty(sizeValueList)) {
                storeProductAttr.setAttrValues(String.join(",", sizeValueList));
                attrList.add(storeProductAttr);
            }
            productRequest.setAttr(attrList);
            productRequest.setAttrValue(attrValueList);
            // 强制写一个 商户id 作为buyer商品标识标识
            productRequest.setMerId(CrmebMerchantEnums.ORANGE.getMerchantId());
            productRequest.setContent(product.getRichDesc());
            // todo 国际编码暂时没有  暂时""处理
            productRequest.setKeyword("");
//            productRequest.setStoreInfo(product.getDesc());
            productRequest.setStoreInfo(product.getRichDesc());
            productRequest.setStoreName(product.getName());
            if(null != storeBrand) {
                productRequest.setBrandId(storeBrand.getId());
                productRequest.setBrandName(storeBrand.getEnName());
            }
            productRequest.setPrice(price);
//            productRequest.setOtPrice(otPrice);
            productRequest.setCost(price);
            productRequest.setSourceCost(price);
            productRequest.setPromoteFlag(false);
            productRequest.setErpPromFlag(true);
            productRequest.setTempId(tempId);

            // 供应商
            Supplier supplier = supplierService.getOne(Wrappers.<Supplier>lambdaQuery()
                    .eq(Supplier :: getBarcode, BarCodeEnum.ORANGE.getCode())
                    .last("LIMIT 1")
            );
            if(null != supplier) {
                productRequest.setSuppliersId(supplier.getId());
                productRequest.setSuppliersName(supplier.getSuppliersName());
            }
            productRequest.setBarCode(barCode);

            productRequest.setImage(imageList.get(0));
            productRequest.setSliderImage(product.getImageList());
            productRequest.setIsShow(true);
            productRequest.setSpecType(true);
            productRequest.setIsEurope(ProductTypeEnum.ORANGE.getCode());
            productRequest.setUnitName(skus.get(0).getUnit());
            productRequest.setLastPushTime(new Date());
            productRequest.setAddTime(Integer.parseInt(String.valueOf(System.currentTimeMillis() / 1000L)));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return productRequest;
    }

}
